package com.security.control.web.controller;

import com.security.control.entity.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 * @author imoot@gamil.com
 * @date 2018/12/15 0015 16:12
 * restful的文件上传与下载
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static final String FOLDER = "I://";

    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        File localFile = new File(FOLDER, new Date().getTime() + ".txt");
        file.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try (InputStream inputStream = new FileInputStream(new File(FOLDER, id + ".txt"));
             OutputStream outputStream = response.getOutputStream();
        ) {
            response.setContentType("application/x-download");//设置内容类型为下载
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");//设置头信息，指定下载名字为test.txt
            IOUtils.copy(inputStream, outputStream);//把文件输入流拷贝到输出流中
            outputStream.flush();
        }
        //try(声明流){相关操作}可以在执行完毕后自动关闭流
    }

}
